﻿
//Array.forEach implementation for IE support..
//https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach
if (!Array.prototype.forEach) {
    Array.prototype.forEach = function (callback, thisArg) {
        var T, k;
        if (this == null) {
            throw new TypeError(" this is null or not defined");
        }
        var O = Object(this);
        var len = O.length >>> 0; // Hack to convert O.length to a UInt32
        if ({}.toString.call(callback) != "[object Function]") {
            throw new TypeError(callback + " is not a function");
        }
        if (thisArg) {
            T = thisArg;
        }
        k = 0;
        while (k < len) {
            var kValue;
            if (k in O) {
                kValue = O[k];
                callback.call(T, kValue, k, O);
            }
            k++;
        }
    };
}

var apiWebHost = "http://api.djusu.com/";
//if (document.domain.indexOf('localhost') > -1) {
//  apiWebHost = "http://localhost:5428/";
//}


var ComFunJS = {
    APIURL: function (action) {
        return apiWebHost + action;
    },
    FilePath: function (fileid, wh) {
        fileid = fileid + "";
        if (!fileid || fileid == "") {
            return "";
        }
        //如果是http路径，则直接返回
        if (fileid.toLowerCase().indexOf("http:") > -1) {
            return fileid;
        }
        if (fileid) {
            if (wh) {
                return "http://api.djusu.com/" + "File/thum/" + fileid.split(',')[0] + wh;//缩略图,默认200*200，可以传宽高/200/200
            }
            else {
                return "http://api.djusu.com/" + "File/thum/" + fileid.split(',')[0];
            }
        }
        else {
            return "";
        }
    },
    //FileThum: function (fileid) { //缩略图,默认200*200，可以传宽高/200/200   整合到FilePath了
    //    return apiWebHost + "/File/thum/" + fileid;
    //},
    getQueryString: function (name, defauval) {//获取URL参数,如果获取不到，返回默认值，如果没有默认值，返回空格
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) { return unescape(decodeURI(r[2])); }
        else {
            return defauval || "";
        }
    },
    //格式化日期，format:格式，默认yyyy-MM-dd,date时间，默认当前时间
    getNowDate: function (format, date) {
        if (!format) {
            format = "yyyy-MM-dd";
        }

        var now = new Date();
        if (date) {
            now = new Date(Date.parse(date.replace(/-/g, '/')));
        }

        var year = now.getFullYear();       //年
        var month = now.getMonth() + 1;     //月
        var day = now.getDate();            //日
        var hh = now.getHours();
        var mm = now.getMinutes();
        var ss = now.getSeconds();

        var clock = year + "-";

        switch (format) {
            case "yyyy-MM-dd": {
                if (month < 10)
                    clock += "0";
                clock += month + "-";
                if (day < 10) {
                    clock += "0";
                }
                clock += day;
            }
                break;
            case "yyyy-MM": {
                if (month < 10)
                    clock += "0";
                clock += month;
            }
                break;

            case "yyyy-MM-dd HH:mm:ss": {
                if (month < 10)
                    clock += "0";
                clock += month + "-";
                if (day < 10) {
                    clock += "0";
                }
                clock += day + " ";

                if (hh < 10)
                    clock += "0";
                clock += hh + ":";
                if (mm < 10)
                    clock += "0";
                clock += mm + ":";
                if (ss < 10)
                    clock += "0";
                clock += ss;
            }
                break;
            case "yyyyMMddHHmmss": {
                clock = year;
                if (month < 10)
                    clock += "0";
                clock += month;
                if (day < 10) {
                    clock += "0";
                }
                clock += day;

                if (hh < 10)
                    clock += "0";
                clock += hh;
                if (mm < 10)
                    clock += "0";
                clock += mm;
                if (ss < 10)
                    clock += "0";
                clock += ss;
            }
                break;
            case "MMddHHmm": {
                clock = "";
                var nowdata = new Date();
                var nowYear = nowdata.getFullYear();
                var nowMonth = nowdata.getMonth() + 1;
                var nowDay = nowdata.getDate();
                var nowdatastr = nowYear + nowMonth + nowDay;
                var datastr = year + month + day;
                if (nowdatastr == datastr) {
                    clock += hh + ":";
                    clock += mm;
                }
                else {
                    clock += month + "-";
                    clock += day + " ";
                    clock += hh + ":";
                    clock += mm;
                }
            }
                break;
        }

        return clock;

    },
    //获取上一周的日期，从周一到周日
    getLastWeekDate: function () {
        var now = new Date();
        //var week = new Array();
        var currentWeek = now.getDay();

        if (currentWeek == 0) {
            currentWeek = 7;
        }
        var monday = now.getTime() - (currentWeek + 6) * 24 * 60 * 60 * 1000; //星期一
        var tuesday = now.getTime() - (currentWeek + 5) * 24 * 60 * 60 * 1000; //星期二
        var wednesday = now.getTime() - (currentWeek + 4) * 24 * 60 * 60 * 1000; //星期三
        var thursday = now.getTime() - (currentWeek + 3) * 24 * 60 * 60 * 1000; //星期四
        var friday = now.getTime() - (currentWeek + 2) * 24 * 60 * 60 * 1000; //星期五
        var saturday = now.getTime() - (currentWeek + 1) * 24 * 60 * 60 * 1000; //星期六
        var sunday = now.getTime() - (currentWeek) * 24 * 60 * 60 * 1000;   //星期日

        //week = weektoday(monday, tuesday, wednesday, thursday, friday, saturday, sunday);

        return {
            monday: monday, sunday: sunday
        }

    },
    setCookie: function (name, value, t) {  //设置cookie，默认保存7天
        var Days = 7;
        var exp = new Date();
        if (t) {
            exp.setTime(exp.getTime() + parseInt(t) * 24 * 60 * 60 * 1000);
        } else {
            exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
        }
        document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/";
    },
    getCookie: function (name) {//获取cookie
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg))
            return unescape(arr[2]);
        else
            return null;
    },
    delCookie: function (name) { //删除cookie
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval = ComFunJS.getCookie(name);
        if (cval != null) {
            document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString() + ";path=/;";
        }
    },
    getNowUser: function () {
        return ComFunJS.getCookie("bwusertoken");
    },
    setNowUser: function (obj) {
        if (ComFunJS.getCookie("bwusertoken")) {
            ComFunJS.delCookie("bwusertoken");
        }
        ComFunJS.setCookie("bwusertoken", obj, 7);
    },
    delNowUser: function () {
        ComFunJS.delCookie("bwusertoken");
    },
    //layer控件扩展
    //警告
    showAlert: function (msg) {
        var msg = msg || "出错了";
        layer.open({
            content: msg,
            style: 'color:red; border:none;',
            btn: '确定'
        });

    },
    //信息提示，2秒消失
    showMsg: function (msg) {
        var msg = msg || "提示";
        layer.open({
            content: msg,
            anim: 'up',
            style: 'width:90%',
            skin: 'msg',
            time: 2,
        });
    },
    //确认
    showConfirm: function (msg, yes, no, yesmsg, nomsg) {
        var ym = '确认';
        var nm = '取消';
        if (yesmsg) {
            ym = yesmsg;
        }
        if (nomsg) {
            nm = nomsg;
        }
        var lyindex = layer.open({
            content: msg,
            btn: [ym, nm],
            yes: function (index) {
                layer.close(lyindex);
                return yes && yes.call(this);
            },
            no: function (index) {
                return no && no.call(this);
            }
        });
    },
    //底部弹出确认
    showConfirm2: function (msg, yes, btn1, no, btn2) {
        var btn1 = btn1 || "确认";
        var btn2 = btn2 || "取消";
        var lyindex = layer.open({
            content: msg,
            btn: [btn1, btn2],
            skin: 'footer',
            yes: function (index) {
                layer.close(lyindex);
                return yes && yes.call(this);
            },
            no: function (index) {
                return no && no.call(this);
            }
        });
    },
    //加载中
    showLoading: function (msg) {
        var msg = msg || "玩命加载中";
        layer.open({
            type: 2,
            content: msg,
            shadeClose: false,
            shade: 'background-color: rgba(0,0,0,.3)'
        })
    },
    //关闭layer
    close: function (lyindex) {
        if (lyindex) {
            layer.close(lyindex);
        } else {
            setTimeout("layer.closeAll()", 1500);
        }
    },
    showValidSMS: function (tel, type, callback) {
        var height = height || "200";
        var content = '<div class="tanbox" style="top:10px;">';
        content += ' <h1>输入图片验证码<span class="closediy">×</span></h1>';
        content += '<h2 id="tipmsg">点击验证码可刷新验证码</h2>';
        content += '<div class="validate clearfix">';
        content += ' <input type="text" name="pass" id="validateCode" placeholder="验证码" maxlength="6">';
        content += ' <img id="imgCode" src="" alt="验证码">';
        content += ' </div>';
        content += ' <p id="sendSMS">验证并获取</p>';
        content += ' </div>';

        var pagei = layer.open({
            type: 1,
            content: content,
            shadeClose: false,
            style: 'width:100%;height:' + height + 'px;background:none;',
            anim: 0,
            success: function (layero) {
                var guid = ComFunJS.guid();
                $(".tanbox").find(".closediy").click(function () {
                    layer.close(pagei);
                })
                $(".tanbox").find("#imgCode").attr("src", ComFunJS.APIURL("Verification/Graphics/" + guid + "?p=" + Math.random()));
                $(".tanbox").find("#imgCode").click(function () {
                    $(".tanbox").find("#imgCode").attr("src", ComFunJS.APIURL("Verification/Graphics/" + guid + "?p=" + Math.random()));
                })


                $(".tanbox").find("#sendSMS").click(function () {
                    var vcode = $(".tanbox").find("#validateCode").val()
                    if (vcode == "") {
                        $(".tanbox").find("#tipmsg").text("请输入验证码");
                        $(".tanbox").find("#tipmsg").css("color", "red");

                    } else {

                        $.getJSON(ComFunJS.APIURL("Verification/Validate/" + guid + "/" + vcode + "/" + type + "/" + tel), function (r) {
                            if (r.error == "") {
                                layer.close(pagei);
                                ComFunJS.showMsg("请输入手机收到的验证码");
                                return callback.call(this, { "guid": guid, "vcode": vcode });
                            } else {
                                $(".tanbox").find("#tipmsg").text(r.error);
                                $(".tanbox").find("#tipmsg").css("color", "red");
                            }
                        });

                    }
                })
            }

        });
    },
    //显示html信息
    showHtml: function (html, callback) {
        var title = title || "信息";
        var height = height || "200";

        layer.open({
            type: 1,
            content: html,
            shadeClose: true,
            style: 'width:100%;height:' + height + 'px;background-color:none;',
            anim: 'up',
            success: function (layero) {
                if (callback) {
                    return callbact.call(this, layero);
                }
            }

        });
    },
    //layer控件扩展
    strToIds: function (text) {
        var ids = [];
        if (text) {
            text.split(',').forEach(function (item, index) {
                ids.push({
                    "ID": "" + item + ""
                });
            })
        }
        return ids;
    },
    fileUpload: function (callback) {
        ComFunJS.showFormBtn("请选择文件", "/fileupload.html", "500", "400", function (layero, index, btdom) {
            var iframeWin = layero.find('iframe')[0];
            var data = iframeWin.contentWindow.getFileData();
            if (data && data.length > 0) {
                $.post(ComFunJS.APIURL("webbase/addfile"), {
                    P1: JSON.stringify(data)
                }, function (result) {
                    //var r = JSON.parse(result);
                    r = result;
                    if (r.error == "") {

                        layer.close(index);
                        return callback.call(this, r.result);
                    }
                })
            } else {
                layer.close(index);
            }

        })
    },
    initForm: function () {

    },
    //获取Token
    GetToken: function () {
        var token = ComFunJS.getNowUser();
        if (!token) {
            //这里可以跳转到登录页
            //alert("用户还未登录")
        }
        return token;
    },
    //判断是否登录
    IsLogin: function () {
        if (ComFunJS.getNowUser()) {
            return true;
        } else {
            return false;
        }
    },
    //Get方式访问带验证的API
    getJSON: function (url, data, callback) {
        if (typeof (data) == "function") {
            callback = data;
            data = null;
        }
        $.ajax({
            type: "GET",
            url: ComFunJS.APIURL(url),
            dataType: "json",
            data: data,
            headers: {
                Authorization: ComFunJS.GetToken()
            },
            success: function (result) {
                if (result.error == "用户未登录") {
                    ComFunJS.delNowUser();
                    return callback & callback.call(this, result);
                } else {
                    return callback & callback.call(this, result);
                }
            }
        });
    },
    //Post方式访问带验证的API
    postJSON: function (url, data, callback) {
        if (typeof (data) == "function") {
            callback = data;
            data = null;
        }
        $.ajax({
            type: "POST",
            url: ComFunJS.APIURL(url),
            dataType: "json",
            data: data,
            headers: {
                Authorization: ComFunJS.GetToken()
            },
            success: function (result) {
                if (result.error == "用户未登录") {
                    ComFunJS.delNowUser();
                    return callback & callback.call(this, result);
                } else {
                    return callback & callback.call(this, result);
                }
            }
        });
    },
    GetDomain: function () {
        var host = window.location.host;
        if (host.lastIndexOf("/") == -1) {
            host += "/";
        }
        return "http://" + host;
    },
    //微信JSAPI授权
    GETWXJSSDK: function (wxtitle, wxdesp, imgUrl, urllink, callback, othercallback) {
        var title = document.title;
        if (wxtitle) {
            title = wxtitle;
        }
        var desp = title;
        if (wxdesp) {
            desp = wxdesp;
        }
        if (imgUrl) {
            imgUrl = ComFunJS.GetFile(imgUrl, "/200/200");
        }
        else {
            imgUrl = "http://www.djusu.com/mobile/image/images/alogo_03.png";
        }
        var link = window.location.href.split('#')[0];
        if (urllink) {
            link = urllink;
        }
        $.post(ComFunJS.APIURL("weixin/jsapi"), { url: encodeURIComponent(window.location.href.split('#')[0]) }, function (r) {
            if (r.error == "") {
                wx.config({
                    debug: false,
                    appId: r.result.appId,
                    timestamp: r.result.timestamp,
                    nonceStr: r.result.noncestr,
                    signature: r.result.signature,
                    jsApiList: [
                      'checkJsApi',
                      'onMenuShareTimeline',
                      'onMenuShareAppMessage',
                      'onMenuShareQQ',
                      'onMenuShareWeibo',
                      'hideMenuItems',
                      'showMenuItems',
                      'hideAllNonBaseMenuItem',
                      'showAllNonBaseMenuItem',
                      'translateVoice',
                      'startRecord',
                      'stopRecord',
                      'onRecordEnd',
                      'playVoice',
                      'pauseVoice',
                      'stopVoice',
                      'uploadVoice',
                      'downloadVoice',
                      'chooseImage',
                      'previewImage',
                      'uploadImage',
                      'downloadImage',
                      'getNetworkType',
                      'openLocation',
                      'getLocation',
                      'hideOptionMenu',
                      'showOptionMenu',
                      'closeWindow',
                      'scanQRCode',
                      'chooseWXPay',
                      'openProductSpecificView',
                      'addCard',
                      'chooseCard',
                      'openCard'
                    ]
                })
                wx.ready(function () {
                    //分享给朋友分享到朋友圈
                    wx.onMenuShareTimeline({
                        title: title, // 分享标题
                        link: link, // 分享链接
                        imgUrl: imgUrl, // 分享图标
                        success: function () {
                            return callback && callback.call(this, "WX");
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                        }
                    });
                    //分享给朋友
                    wx.onMenuShareAppMessage({
                        title: title, // 分享标题
                        desc: desp, // 分享描述
                        link: link, // 分享链接
                        imgUrl: imgUrl, // 分享图标
                        type: '', // 分享类型,music、video或link，不填默认为link
                        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                        success: function () {
                            return callback && callback.call(this, "WXZONE");
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                        }
                    });
                    //分享到QQ
                    wx.onMenuShareQQ({
                        title: title, // 分享标题
                        desc: desp, // 分享描述
                        link: link, // 分享链接
                        imgUrl: imgUrl, // 分享图标
                        success: function () {
                            return callback && callback.call(this, "QQ");
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                        }
                    });
                    //分享到腾讯微博
                    wx.onMenuShareWeibo({
                        title: title, // 分享标题
                        desc: title, // 分享描述
                        link: link, // 分享链接
                        imgUrl: imgUrl, // 分享图标
                        success: function () {
                            return callback && callback.call(this, "TXWEIBO");
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                        }
                    });
                    //分享到QQ空间
                    wx.onMenuShareQZone({
                        title: title, // 分享标题
                        desc: desp, // 分享描述
                        link: link, // 分享链接
                        imgUrl: imgUrl, // 分享图标
                        success: function () {
                            return callback && callback.call(this, "QQZONE");
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                        }
                    });
                    //获取用户网络状态
                    wx.getNetworkType({
                        success: function (res) {
                            var networkType = res.networkType; // 返回网络类型2g，3g，4g，wifi
                            return othercallback && othercallback.call(this, networkType);
                        }
                    });
                })
                wx.error(function (res) {

                })
            }
        })
    },
    //规则验证
    regMatch: function (type, value) {
        var reg;
        switch (type) {
            case "tel":
                {
                    reg = /^1[3|4|5|8|7]\d{9}$/;
                }
                break;
        }
        return reg.test(value);

    },
    toUtf8: function (str) {
        var out, i, len, c;
        out = "";
        len = str.length;
        for (i = 0; i < len; i++) {
            c = str.charCodeAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) {
                out += str.charAt(i);
            } else if (c > 0x07FF) {
                out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            } else {
                out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            }
        }
        return out;
    },
    guid: function () {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    },
    GetFile: function (fileid, wh) {
        if (!fileid || fileid == "") {
            return "";
        }
        fileid = String(fileid);
        //如果是http路径，则直接返回
        if (fileid.toLowerCase().indexOf("http:") > -1) {
            return fileid;
        }
        return ComFunJS.FilePath(fileid, wh)
    },
    getMS: function (time) {   //秒装换   分:秒
        return time;
        //if (!time) {
        //    return;
        //}
        //var h = 0,
        //m = 0,
        //s = 0,
        //_h = '00',
        //_m = '00',
        //_s = '00';
        //h = Math.floor(time / 3600);
        //time = Math.floor(time % 3600);
        //m = Math.floor(time / 60);
        //s = Math.floor(time % 60);
        //_s = s < 10 ? '0' + s : s + '';
        //_m = m < 10 ? '0' + m : m + '';
        //_h = h < 10 ? '0' + h : h + '';
        //if (_h == '00') {
        //    return _m + ":" + _s;
        //}
        //else {
        //    return _h + ":" + _m + ":" + _s;
        //}
    },
}

function RedirectUrl(url) {
    var data = new Date();
    window.location.href = url + "?time=" + ComFunJS.getNowDate("yyyyMMddHHmmss");
}